<?php
require_once  $_SERVER['DOCUMENT_ROOT']."/../_lib/base/common.php";
require_once SITE_ROOT_PATH."/_lib/classes/class.template.php";
require_once SITE_ROOT_PATH."/_lib/classes/class.hotels.php";
require_once SITE_ROOT_PATH."/_lib/classes/class.destinations.php";
require_once SITE_ROOT_PATH."/_lib/classes/class.exchange_rates.php";
require_once SITE_ROOT_PATH."/_lib/classes/class.bookings.php";
require_once SITE_ROOT_PATH."/_lib/classes/class.countries.php";
require_once SITE_ROOT_PATH."/_lib/classes/class.suppliers.php";
require_once SITE_ROOT_PATH."/_lib/classes/class.SimpleEmailService.php";
require_once SITE_ROOT_PATH."/_lib/classes/controller/BookingHotelController.php";
require_once SITE_ROOT_PATH."/latedeals.ie/hotels/payment_gate.php";

// Start Sessions
session_start();
// to avoid that some warnings are shown to user
// this warnings happens when the user is trying two books each one in different tabs of the browser
// so the sessions is mixing.

error_reporting(E_ERROR | E_PARSE);
// check for session expiration
if(isset($_SESSION["booking"]["details"]["timestamp"]) && $_SESSION["booking"]["details"]["timestamp"] < time() - BOOKING_TIMEOUT) {
  unset($_SESSION["booking"]);
  header("Location: booking_timeout.php");
}

$template = new template();
$template->title = $title;
$template->meta_keywords = $meta_keywords;
$template->meta_description = $meta_description;
$template->section_highlight = "hotels";
$template->breadcrumbs_html = "<li>&rsaquo;</li><li title=\"Hotels\"><a href=\"/hotels/index.html\" title=\"Hotels\">Hotels</a></li><li>&rsaquo;</li><li title=\"Search Results\"><a href=\"/hotels/hotel_results.php\" title=\"Search Results\">Search Results</a></li>";
$template->left_col = false;
$template->show_tos = false;

$results = $_SESSION["hotels_search_results"]["data"];
$hotel = $_SESSION["booking"]["hotel"];
$hotel_id = $_SESSION["booking"]["hotel_id"];
$room_ids = $_SESSION["booking"]["room_ids"];
$booking_details = $_SESSION["booking"]["details"];
$payment = $_SESSION["booking"]["payment"];

switch($_POST['action']){
	default:
                if ($_SESSION['booking']['finished']){
                     header("Location: index.html");                        
                     exit;
                }
                // to avoid that user're doing two books in the same time but in differents tabs of browser
                if ((! is_array($booking_details)) || (! is_array($hotel))){
                    session_destroy();
                    session_start();
                    $_SESSION['booking']['finished'] = true;      
                    header("Location: booking_error.php");   
                    exit;
                }
		$template->ld_head();
		// Show booking page 
		include SITE_ROOT_PATH."/_lib/html/hotel_payment.php";
		$template->ld_foot();
	break;
	case "validate";
                    

            $result = $_SESSION["booking"]["result"];
           if (is_array($result) && $result['error'] == 0)  {
               $_SESSION['booking']['finished'] = true;
               header("Location: booking_confirm.php?sid=".session_id());    
               exit;
           }   

           if (($_SESSION['booking']['finished']) || $_POST['booking_hotel_id'] != $_SESSION['booking']['hotel_id'] ){
               $_SESSION['booking']['finished'] = true;               
               header("Location: booking_error.php");    
               exit;               
           }
  	   $bookings = new bookings();
                
           for($i=1; $i<=$results["rooms_count"]; $i++){
             $total+=$hotel["room_sets"][$i]["rooms"][$room_ids[$i]]["Rate"]    ;  
           }
           $nett_rate = 0;
           for($i=1; $i<=$results["rooms_count"]; $i++){
             $nett_rate+=$hotel["room_sets"][$i]["rooms"][$room_ids[$i]]["RateOrig"]    ;  
           }          
           
           $payment = preprocess_payment_form($_POST, $total, $nett_rate);              
           $payment['total_currency'] = $hotel['currency'];
           $booking_details['supplier_code'] = $hotel["supplier_code"];
           $params = array_merge($booking_details, $payment);
           $params = array_merge($params, map_params($hotel, $room_ids, $params['guests']));
           $bookings->begin_booking($params, true);          
  	   $form_errors = $bookings->validate_payment_form($params);
           
	   if(!empty($form_errors)){
		$my_message = array();
		$my_message['type'] = 'neg';
		$my_message['message'] = "There was a problem with the form";
		$my_message['list'] = $form_errors;
		$GLOBALS['note'] = $my_message;
                $_SESSION['booking']['payment'] = $payment;                
		// Show booking page
		$template->ld_head();
		include SITE_ROOT_PATH."/_lib/html/hotel_payment.php";
		$template->ld_foot();
	    }else{
      // store valid payment details                
                $_SESSION['booking']['payment'] = $payment;
                $result = process_booking();                             
		// avoid form being resubmitted repeat when refreshing browser               
                if ($result['error'] == 0){                    
                    $bookings->save_booking_details();
                    session_destroy();
                    session_start();
                    $_SESSION['booking']['finished'] = true;  
                    $_SESSION["booking"]["booking_id"] = $bookings->getBooking_id();   
                    send_notification_email($booking_details['lead_epost1']);
                    header("Location: booking_confirm.php?sid=".session_id());   
                    exit;
                 }   
                   else {
                        session_destroy();
                        session_start();
                        $_SESSION['booking']['finished'] = true;  
                        $_SESSION["booking"]["booking_id"] = $bookings->getBooking_id(); 
                        header("Location: booking_error.php");   
                        exit;
                   }
                   exit;

	    }
	break;
}

function preprocess_payment_form($params, $total, $nett_rate) {
 
    $params["cc_expdate"] = $params["card_expiry_month"].$params["card_expiry_year"];
    $params['total'] = $total;
    $params['surcharge'] = ($params['cc_type'] != 'laser' ? round((($params['total'] * CREDIT_CARD_FREE)/100), 2,PHP_ROUND_HALF_UP ) : 0);
    $params['nett_rate'] = $nett_rate; 
    $params['sale_price'] = $params['total'] ; 
    $params['total_price']= $params['sale_price'] + $params['surcharge']; 
    
    return $params;
}

function map_params($hotel, $room_ids,$guests){
    $rooms = array();
    $num_rooms = $_SESSION["hotels_search_results"]["data"]["search_params"]["no_rooms"];
    $num_night = $_SESSION["hotels_search_results"]["data"]["search_params"]["nights"];
    for ($index = 1; $index <= $num_rooms; $index++) {
         $room = array ("room_type" => $hotel["room_sets"][$index]["rooms"][$room_ids[$index]]["Type"],
                        "num_adult" => $hotel["room_sets"][$index]["adults"],
                        "num_child" => $hotel["room_sets"][$index]["children"],
                        "sale_price" => $hotel["room_sets"][$index]["rooms"][$room_ids[$index]]["Rate"],   
                        "nett_rate" => $hotel["room_sets"][$index]["rooms"][$room_ids[$index]]["RateOrig"],   
                        "board_basis_code" => $hotel["room_sets"][$index]["rooms"][$room_ids[$index]]["Board"],
                        "room_id" =>  $hotel["room_sets"][$index]["rooms"][$room_ids[$index]]["ID"],
                        "guests" => $guests[$index]);
         $rooms[$index] = $room;
    }
    return array ("num_night" => $num_night, 
                  "num_room" => $num_rooms, 
                  "check_in_date" => $_SESSION["hotels_search_results"]["data"]["search_params"]["arrival_date"], 
                  "check_out_date" => $_SESSION["hotels_search_results"]["data"]["search_params"]["arrival_date"] + ($num_night * 86400),
                  "rooms" => $rooms,
                  "hotel_id" =>$hotel['hotel_id']);
    
    
    
       

    
}
?>